import java.io.*;
import java.net.*;
import java.util.*;
import java.sql.*;

public class UserServerThread extends Thread{
   
    private BufferedWriter writer;
    private BufferedReader input;
    private Encryption enc;
    private Socket socket;

    public UserServerThread(Socket socket){
        enc = new Encryption();
        this.socket = socket;
    }

    public void run(){
        try{

            writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String fileName = input.readLine();
            fileName = enc.decrypt(fileName);
            
            /* Get file size */
            File myFile = new File("./files/"+fileName);
            long size = myFile.length();
            System.out.println("Pediu o arquivo: "+fileName+" de tamanho: "+size);

            /* Enviar tamanho */
            String msgm = "Size_"+size;
            msgm = enc.encrypt(msgm);
            writer.write(msgm);
            writer.newLine();
            writer.flush();
            
            /* Chamar funcao que realiza a transferencia */
            Transfer(socket, myFile, size);

        }catch(Exception e){e.printStackTrace();}
    }
    
    public void Transfer(Socket socket, File myFile, long size){

        try{
            DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
            FileInputStream input_file = new FileInputStream(myFile);

            int read=0;
            int count=0;

            System.out.println("Sendind");

            while((read = input_file.read())!=-1){
                dos.writeByte(read);
                count++;
            }

            dos.flush();
            input_file.close();

        }catch(Exception e){e.printStackTrace();}
    }


}
